package com.itheima.service.impl;

import com.itheima.service.CreatCodeService;
import com.itheima.utils.CheckUtils;
import com.itheima.utils.ValidateCodeUtils;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * @author Jack
 * @date 2020/7/9 22:24
 */


@Service
public class CreatCodeServiceImpl implements CreatCodeService {

    @Autowired
    private RedisTemplate redisTemplate;


    /**
     * @param info
     * @return
     * @// TODO: 2020/7/10  Redis过期时间设置为5分钟，将手机号或者邮箱存为Key 验证码存为Value 已测试 无异常
     *
     */
    @Override
    public String createCode(String info) {

        boolean flag = false;
        //判断是否含有@
        if (info.contains("@")) {

            flag = CheckUtils.checkEmail(info);
        } else {
            flag = CheckUtils.checkMobileNumber(info);
        }

        //如果为false 直接返回错误提示
        if (!flag) {
            throw new RuntimeException("手机或邮箱数据校验失败");
        }

        String code = "";

        if (flag) {
            code = ValidateCodeUtils.generateValidateCode4String(4);
        }

        //将手机号或者邮箱存为Key 验证码存为Value
        redisTemplate.opsForValue().set(info, code);

        //设置Redis验证码过期时间为5分钟
        redisTemplate.expire(info, 5, TimeUnit.MINUTES);

        Long expire = redisTemplate.boundHashOps(info).getExpire();
        System.out.println("redis有效时间：" + expire + "分钟");

        return code;
    }
}
